package com.example.system.config;

import com.auth0.jwt.JWT;
import com.example.auth.user.entity.SystemUser;
import com.example.auth.user.service.SystemUserService;
import com.example.system.jwt.TokenUtil;
import com.mysql.cj.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author hl
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    protected Logger logger = LoggerFactory.getLogger(AuthenticationInterceptor.class);

    @Autowired
    SystemUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) {
        // 从 cookie 中取出 token
        String token = null;
        Cookie[] cookies = httpServletRequest.getCookies();
        if(cookies != null){
            for (Cookie cookie:cookies){
                if(cookie.getName().equals("token")){
                    token = cookie.getValue();
                }
            }
        }
        String path = httpServletRequest.getContextPath();
        // 执行认证
        if (StringUtils.isNullOrEmpty(token)) {
            try {
                httpServletResponse.sendRedirect(path+"/login");
            } catch (IOException e) {
                e.printStackTrace();
            }
            logger.error("无token，请重新登录");
            return false;
        }
        boolean result = TokenUtil.verify(token);
        String userId = JWT.decode(token).getClaim("userId").asString();
        if(result){
            logger.info("token验证通过");
        } else {
            logger.info("token验证未通过");
            return false;
        }
        SystemUser user = userService.getById(userId);
        if (user == null) {
            try {
                httpServletResponse.sendRedirect("/login");
            } catch (IOException e) {
                e.printStackTrace();
            }
            logger.error("用户不存在，请重新登录");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }
}